package william.list;

/**
 * @author ZhangShenao
 * @date 2024/4/30
 * @description <a href="https://leetcode.cn/problems/rotate-list/description/?envType=study-plan-v2&envId=top-interview-150">...</a>
 */
public class Leetcode61_旋转链表 {
    private class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    /**
     * 采用先闭合成环,后断开的思路
     * Step1: 遍历链表,获取链表的长度为N
     * Step2: 判断旋转的次数k是否为N的整数倍,如果是,则无需处理,将链表原样返回
     * Step3: 将链表首位相连,组成环
     * Step4: 旋转后,新链表的尾节点为第N-(k % N)个节点,获取该节点
     * Step5: 尾节点的next即为新的头结点,将尾节点的next置为null,并返回新头节点
     * <p>
     * 时间复杂度O(N) 需要遍历两次链表
     * 空间复杂度O(1)
     */
    public ListNode rotateRight(ListNode head, int k) {
        //边界条件校验
        if (head == null || k <= 0) {
            return head;
        }

        //遍历链表,获取链表的长度为N
        int N = 1;
        ListNode tail = head;
        while (tail.next != null) {
            ++N;
            tail = tail.next;
        }

        if (k % N == 0) {    //旋转的次数为链表长度的整数倍,无需处理,将链表原样返回
            return head;
        }

        //将链表首位相连,组成环
        tail.next = head;

        //旋转后,新链表的尾节点为第N-(k % N)个节点,获取该节点
        int moved = N - (k % N);
        ListNode rotateTail = head;
        for (int i = 0; i < moved - 1; i++) {
            rotateTail = rotateTail.next;
        }

        //尾节点的next即为新的头结点,将尾节点的next置为null,并返回新头节点
        ListNode rotateHead = rotateTail.next;
        rotateTail.next = null;
        return rotateHead;
    }
}
